package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class MServerSocket {

	private ServerSocket serverSocket;

	private ExecutorService pool;

	public MServerSocket(int port) {
		try {
			// 打开服务绑定端口
			this.serverSocket = new ServerSocket(port);
			// 构造一个固定数目的线程池，数目为CPU的线程个数
			this.pool = Executors.newFixedThreadPool(Runtime.getRuntime()
					.availableProcessors());

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void start() {
		while (true) {
			try {
				Socket socket = this.serverSocket.accept();
				this.pool.execute(new MSocket(socket));
			} catch (IOException e) {
				e.printStackTrace();
				break;
			}
		}

	}

	public void close() {
		try {
			this.serverSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
